<template>
    <div>
        <h3 style="margin: 10px 0;">攻击录屏列表</h3>
        <Table border :columns="screenFileCol" :data="row"></Table>
        <Modal v-model="screenRecordModal" title="录屏回放" footer-hide :width="1366"
	        @on-cancel="cancelModal()">
	        <!-- Display -->
	        <div id="player">
		        <div id="display" style="overflow: hidden;">
		        	<!--<div class="notification-container">
	                    <div class="seek-notification">
	                        <p>
	                            Seek in progress...
	                            <button id="cancel-seek">Cancel</button>
	                        </p>
	                    </div>
	                </div>-->
		        </div>
		        <!-- Player controls -->
	            <div class="controls">
	                <button id="play-pause" class="ivu-btn ivu-btn-default ivu-btn-small">播放</button>
	                <!--<button id="live">Live</button>-->
	                <input id="position-slider" type="range">
	                <span id="position">00:00</span>
	                <span>/</span>
	                <span id="duration">00:00</span>
	            </div>
            </div>
	    </Modal>
    </div>
</template>
<script>
	import Guacamole from '@/assets/minejs/all.min'
    import cookieUse from '@/libs/cookie.js'
    export default {
        props:{
            row:Array,
        },
        data () {
            return {
            	screenRecordModal:false,
                screenFileCol:[
                    {
                        title:'序号',
                        type:'index',
                        width:60,
                        align:'center'
                    },
                    {
                        title:"用户名",
                        key:'userName',
                    },
                    {
                        title:"虚拟机名称",
                        key:'name',
                    },
                    {
                        title:"连接时间",
                        key:'connectTime',
                    },
                    {
                        title:"断开时间",
                        key:'disconnectTime',
                    },
                    {
                        title:'录屏回放',
                        key:'down',
                        render:(h,params)=>{
                            return h('div',[
                                h('Button', {
                                    props: {
                                        type: 'primary',
                                        size: 'small',
                                    },
                                    on: {
                                        'click': ()=>{
                                            this.initPlayer(params.row.id)
                                        },
                                    }
                                }, '录屏回放')
                            ])
                        }
                    },
                ], 
            }
        },
        created(){

        },
        mounted(){

        },
        methods:{
            initPlayer(sessionId){
            /**
             * The URL of the Guacamole session recording which should be played back.
             *
             * @constant
             * @type String
             */
            this.screenRecordModal = true;
            var token = cookieUse.getCookie('desig-token');//this.GetQueryString("token");
            // var token = "02f3a158b81347dba1526d485389c614";
            document.cookie = 'token=' +token
            if (!token) {
                //alert('文件为空');
                this.$Message.error('文件为空');
                this.screenPlaybackMd=false;
                return;
            }
            let crheetian = this.baseURL;//"http://172.18.100.1:18769/"
            // console.log(token)
            var param = 'token=' + token;
            // var RECORDING_URL = '/home/access/recording/8d7b998856a04642b760f24cece582d7.guac';
            var RECORDING_URL = crheetian+'/access/sessions/'+sessionId+"/recording";
            // var RECORDING_URL = '/api/access/record?id='+ this.currRecordId;

            /**
             * The element representing the session recording player.
             *
             * @type Element
             */
            var player = document.getElementById('player');
            
            /**
             * The element which will contain the recording display.
             *
             * @type Element
             */
            var display = document.getElementById('display');

            /**
             * Play/pause toggle button.
             *
             * @type Element
             */
            var playPause = document.getElementById('play-pause');
            // playPause.trigger('click');

            var live = document.getElementById('live');

            /**
             * Button for cancelling in-progress seek operations.
             *
             * @type Element
             */
//          var cancelSeek = document.getElementById('cancel-seek');

            /**
             * Text status display indicating the current playback position within the
             * recording.
             *
             * @type Element
             */
            var position = document.getElementById('position');

            /**
             * Slider indicating the current playback position within the recording,
             * and allowing the user to change the playback position.
             *
             * @type Element
             */
            var positionSlider = document.getElementById('position-slider');

            /**
             * Text status display indicating the current length of the recording.
             *
             * @type Element
             */
            var duration = document.getElementById('duration');

            /**
             * The tunnel which should be used to download the Guacamole session
             * recording.
             *
             * @type Guacamole.Tunnel
             */
                 var tunnel = new Guacamole.StaticHTTPTunnel(RECORDING_URL);
            //var tunnel = new Guacamole.WebSocketTunnel(RECORDING_URL);

            /**
             * Guacamole.SessionRecording instance to be used to playback the session
             * recording.
             *
             * @type Guacamole.SessionRecording
             */
            var recording = new Guacamole.SessionRecording(tunnel);
            this.recording  = recording;
            /**
             * The Guacamole.Display which displays the recording during playback.
             *
             * @type Guacamole.Display
             */
            var recordingDisplay = recording.getDisplay();

            /**
             * Converts the given number to a string, adding leading zeroes as necessary
             * to reach a specific minimum length.
             *
             * @param {Numer} num
             *     The number to convert to a string.
             *
             * @param {Number} minLength
             *     The minimum length of the resulting string, in characters.
             *
             * @returns {String}
             *     A string representation of the given number, with leading zeroes
             *     added as necessary to reach the specified minimum length.
             */
            var zeroPad = function zeroPad(num, minLength) {

                // Convert provided number to string
                var str = num.toString();

                // Add leading zeroes until string is long enough
                while (str.length < minLength)
                    str = '0' + str;

                return str;

            };

            /**
             * Converts the given millisecond timestamp into a human-readable string in
             * MM:SS format.
             *
             * @param {Number} millis
             *     An arbitrary timestamp, in milliseconds.
             *
             * @returns {String}
             *     A human-readable string representation of the given timestamp, in
             *     MM:SS format.
             */
            var formatTime = function formatTime(millis) {

                // Calculate total number of whole seconds
                var totalSeconds = Math.floor(millis / 1000);

                // Split into seconds and minutes
                var seconds = totalSeconds % 60;
                var minutes = Math.floor(totalSeconds / 60);

                // Format seconds and minutes as MM:SS
                return zeroPad(minutes, 2) + ':' + zeroPad(seconds, 2);

            };

            // Add playback display to DOM
            display.appendChild(recordingDisplay.getElement());

            // Begin downloading the recording
            console.log(param)
            recording.connect(param);

            // If playing, the play/pause button should read "Pause"
            recording.onplay = function () {
                playPause.textContent = '暂停';
            };

            // If paused, the play/pause button should read "Play"
            recording.onpause = function () {
                playPause.textContent = '播放';
            };

            // Toggle play/pause when display or button are clicked
            display.onclick = playPause.onclick = function () {
                if (!recording.isPlaying())
                    recording.play();
                else
                    recording.pause();
            };

            // Resume playback when cancel button is clicked
//          cancelSeek.onclick = function cancelSeekOperation(e) {
//              recording.play();
//              player.className = '';
//              e.stopPropagation();
//          };

            // Fit display within containing div
            recordingDisplay.onresize = function displayResized(width, height) {

                // Do not scale if display has no width
                if (!width)
                    return;

                // Scale display to fit width of container
                recordingDisplay.scale(display.offsetWidth / width);

            };

            // Update slider and status when playback position changes
            recording.onseek = function positionChanged(millis) {
                position.textContent = formatTime(millis);
                positionSlider.value = millis;
            };

            // 在五秒内计算如果时常没有变化就跳转到最后的时间

            // Update slider and status when duration changes
            recording.onprogress = function durationChanged(millis) {
                duration.textContent = formatTime(millis);
                positionSlider.max = millis;
                //console.log('获取到新消息');
                if (!recording.isPlaying()){
                    //console.log('获取到新消息，继续播放')
                    recording.play();
                }

            };

            // Seek within recording if slider is moved
            positionSlider.onchange = function sliderPositionChanged() {

                console.log(positionSlider.value);
                // Request seek
                recording.seek(positionSlider.value, function seekComplete() {

                    // Seek has completed
                    player.className = '';

                });

                // Seek is in progress
                player.className = 'seeking';

            };

//          live.onclick = function () {
//
//              // Request seek
//              recording.seek(positionSlider.max, function seekComplete() {
//
//                  // Seek has completed
//                  player.className = '';
//
//              });
//
//              // Seek is in progress
//              player.className = 'seeking';
//          }
        },
        cancelModal(){
            let display = document.getElementById("display");
            this.recording.pause();
            let childs = display.childNodes;
            for(let i = childs.length - 1; i >= 0; i--) { 
                if(childs[i].className == 'notification-container'){
                    return;
                }else{
                    display.removeChild(childs[i]); 
                }
            };
        },
        }
    }
</script>
<style scoped>
    .controls{
	  	display: flex;
	  	margin-top:10px;
	  	align-items: center;
	}
	#position-slider{
	  	flex:1 1 auto;
	  	margin:0 10px;
	}
</style>
